package com.xh.bussiness.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xh.bussiness.system.bean.request.GroupSubjectRequest;
import com.xh.bussiness.system.model.Dictionary;
import com.xh.bussiness.system.model.GroupSubject;
import com.xh.bussiness.system.dao.GroupSubjectMapper;
import com.xh.bussiness.system.service.IDictionaryService;
import com.xh.bussiness.system.service.IGroupSubjectService;
import com.xh.core.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.xh.core.bean.XhPage;
import com.xh.core.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户组学科关系 服务实现类
 * </p>
 *
 * @author Pitt
 * @since 2020-11-23
 */
@Service
public class GroupSubjectServiceImpl extends BaseServiceImpl<GroupSubjectMapper, GroupSubject> implements IGroupSubjectService {

    @Autowired
    private IDictionaryService dictionaryService;

    @Override
    public XhPage queryGroupSubjectPage(XhPage page, GroupSubjectRequest bean) {
        QueryWrapper qw=new QueryWrapper<GroupSubject>();
        //拼装条件
        qw=prepareParams(bean, qw);

        return (XhPage) this.dao.selectPage(page,qw);
    }

    @Override
    public List queryGroupSubject(GroupSubjectRequest bean) {
        QueryWrapper qw=new QueryWrapper<GroupSubject>();
        //拼装条件
        qw=prepareParams(bean, qw);

        return this.dao.selectList(qw);
    }

    @Override
    public List<GroupSubject> queryGroupSubjectByGroupId(String groupId) {
        QueryWrapper<GroupSubject> qw = new QueryWrapper<>();
        qw.eq("group_id", groupId);
        List<Dictionary> subjects = dictionaryService.queryByTypeCode("SUBJECT");
        List<String> subjectCodes = new ArrayList<>();
        if(!subjects.isEmpty()){
            subjectCodes = subjects.stream().map(Dictionary :: getCode).collect(Collectors.toList());
            qw.in("subject_code",subjectCodes);
        }
        return this.dao.selectList(qw);
    }

    @Override
    public boolean deleteGroupSubjectByGroupId(String groupId) {
        return this.dao.deleteByGroupId(groupId);
    }

    /**
     * 准备条件
     * @param bean
     * @param qw
     */
    private QueryWrapper prepareParams(GroupSubjectRequest bean, QueryWrapper qw) {
        if(bean.getIds()!=null&&bean.getIds().length>0){
            qw.in("id",bean.getIds());
        }
        if(!bean.getGroupIds().isEmpty()){
            qw.in("group_id",bean.getGroupIds());
        }
        return qw;
    }

    @Override
    public List<String> queryGroupSubjectCodeByUserId(String userId) {
        return this.dao.queryGroupSubjectByUserId(userId);
    }
}
